<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>启动app</title>
    <style>
        .contenter {
            width: 70%;
            height: auto;
            border-radius: 5px;
            background-color: #ffffff;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin: 0 auto;
            margin-top: 50px;
        }

        .title {
            width: 100%;
            height: 50px;
            background-color: #0dcaf0;
            font-size: 20px;
            border-radius: 5px 5px 0 0;
            color: white;
        }

        .sub_content {
            width: 100%;
            min-height: 550px;
        }

        .select_sub {
            width: 100%;
            height: 50px;
            margin-top: 40px;
            outline: none;
            border-radius: 10px;
            margin-left: 20px;
        }
        .select {
            width: 140px;
            height: 30px;
            border-radius: 5px;
            margin-right: 10px;
            border: 1px solid #ddd;
            background-color: #ffffff;
        }
        .sub {
            width: 60px;
            height: 30px;
            background-color: #0dcaf0;
            border: 0;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }

        input, select {
            outline: none;
            border: none;
        }

        .param-container {
            border-radius: 5px;
            margin-left: 20px;
            margin-bottom: 20px;
        }

        .param-container h3 {
            margin: 0 0 10px 0;
            font-size: 16px;
            color: #333;
        }
        .input_parm {
            width: 100px;
            border-radius: 5px;
            height: 28px;
            border: 1px solid #ddd;
            background-color: #ffffff;
        }

        #sel3 {
            width: 50px;
            height: 29px;
            border-radius: 5px;
            border: 1px solid #ddd;
            background-color: #ffffff;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: #ffffff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        body {
            background-color: #f7f7f7;
        }
    </style>
</head>
<body>
    <div class="contenter">
        <div class="title">
            <p style="padding: 10px; margin-left: 10px;">启动应用</p>
        </div>
        <div class="sub_content">
            <div class="select_sub">
                <select name="sel1" id="sel1" class="select">
                    <option value="">请选择机器人</option>
                </select>
                <select name="sel2" id="sel2" class="select">
                    <option value="">请选择程序</option>
                </select>
            </div>

            <!-- Parameters Table -->
            <div>
                <table id="paramsTable">
                    <thead>
                        <tr>
                            <th>参数名称</th>
                            <th>参数值</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Parameter rows will be added here -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <!-- Include jQuery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
         // 初始请求的 URL
        const initialUrl = 'http://192.168.50.175/v1/yd/robot/status_task';
        // 获取应用程序 URL
        const appUrl = 'http://192.168.50.175/v1/yd/robot/applist_task';
        // 检查任务状态的 URL 模板
        const checkStatusUrlTemplate = 'http://192.168.50.175/v1/yd/robot/check_task_status/%s';
        // 轮询间隔时间（毫秒）
        const pollInterval = 1500;
        
        // 获取uuid
        function getTaskId() {
            $.ajax({
                url: initialUrl,
                method: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response && response.task_id) {
                        const taskId = response.task_id;
                        checkTaskStatus(taskId);
                    } else {
                        console.log("没有获取到有效的task_id");
                        
                    }
                },
                error: function (error) {
                    console.log('初始请求出错: ' + error.statusText);
                }
            });
        }

        // 轮训请求
        function checkTaskStatus(taskId) {

            const checkStatusUrl = checkStatusUrlTemplate.replace('%s', taskId);

            $.ajax({
                url: checkStatusUrl,
                method: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response && response.status === 'SUCCESS') {
                        const resultObj = JSON.parse(response.result);
                        const dataArray = resultObj.data;
                        console.log(type(dataArray))
                        dataArray.forEach(element => {
                            console.log(element);
                            if (element.status === 'idle'){
                                $('#sel1').append(`<option value="${element.name}">${element.name}</option>`);
                            }
                        });
                        
                    } else {
                        setTimeout(() => checkTaskStatus(taskId), pollInterval);
                    }
                },
                error: function (error) {
                    setTimeout(() => checkTaskStatus(taskId), pollInterval);
                }
            });
        }

        function getAppTaskId() {
            $.ajax({
                url: appUrl,
                method: 'POST',
                dataType: 'json',
                success: function (response) {
                    if (response && response.task_id) {
                        const taskId = response.task_id;
                        getAppMessageList(taskId);
                    } else {
                        console.log("没有获取到有效的task_id");
                    }
                },
                error: function (error) {
                    console.log('初始请求出错: ' + error.statusText);
                }
            });
        }

        function getAppMessageList(taskId){
            const checkStatusUrl = checkStatusUrlTemplate.replace('%s', taskId);
            $.ajax({
                url:checkStatusUrl,
                method:'POST',
                dataType:'json',
                success: function (response) {
                    console.log(JSON.stringify(response));
                    
                    const resultObj = JSON.parse(response.result);
                    const dataArray = resultObj.data;
                    if(response && response.status === 'SUCCESS') {
                        dataArray.forEach(element => {
                                $('#sel2').append(`<option value="${element.uuid}">${element.name}</option>`);
                        });
                    }
                
                }
            })
        
        }

        $(document).ready(function () {
            $('#sel2').on('change', function () {
                const selectedId = $(this).val();
                const formData = {
                    uuid: selectedId
                };

                // 发送 AJAX 请求
                $.ajax({
                    url: 'http://192.168.50.175/v1/yd/robot/app_details',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function (response) {
                        const taskId = response.task_id;
                        getPrams(taskId);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('请求出错:', textStatus, errorThrown);
                    }
                });
            });
        });

        function getPrams(taskId){
            const checkStatusUrl = checkStatusUrlTemplate.replace('%s', taskId);
            $.ajax({
                url:checkStatusUrl,
                method:'POST',
                dataType:'json',
                success: function (response) {
                    // const resultObj = JSON.parse(response.result);
                    // const dataArray = resultObj.data;
                    // if(response && response.status === 'SUCCESS') {
                    //     dataArray.forEach(element => {
                    //         console.log(element);
                    //             $('#sel2').append(`<option value="${element.uuid}">${element.name}</option>`);
                    //     });
                    // }
                    if (response && response.status === 'SUCCESS') {
                        console.log(JSON.stringify(response));
                        // const resultObj = JSON.parse(response.result);
                        const dataArray = resultObj.data;
                        dataArray.forEach(element => {
                            console.log(element);
                            // if (element.status === 'idle'){
                            //     $('#sel1').append(`<option value="${element.name}">${element.name}</option>`);
                            // }
                        });
                        
                    } else {
                        setTimeout(() => checkTaskStatus(taskId), pollInterval);
                    }
                },
                error: function (error) {
                    setTimeout(() => checkTaskStatus(taskId), pollInterval);
                }
                
                
            })
        
        }


        


        getTaskId()
        getAppTaskId()    
    </script>
</body>
</html>